<script setup>
import {ref, watch} from "vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";

const alertGroupData = ref([])

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  },
})

const formRef = ref(null)
const form = ref({
  id: -1
})
const GroupList = ref([])

const initFormData = async (id) => {
  const res = await requestUtil.get('role/get/monGroup?id=' + id);
  GroupList.value = res.data.msg;
  form.value.id = id
}

const initGroupData = async () => {
  try {
    const res = await requestUtil.get('role/get/allMonGroup')
    const data = res.data
    console.log(data)
    if (data.code === 200) {
      alertGroupData.value = data.msg
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}

const emits = defineEmits(['update:modelValue'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = async () => {
  let res = await requestUtil.post('role/grant/mon/group', {
    "role_id": form.value.id,
    "groups": GroupList.value
  });
  let data = res.data;
  if (data.code === 200) {
    ElMessage.success('执行成功')
    formRef.value.resetFields()
    handleClose()
  } else {
    ElMessage.error(data.msg)
  }
}
watch(
    () => props.dialogVisible,
    () => {
      initFormData(props.id);
      initGroupData();
    }
)
</script>

<template>
  <el-dialog
      :model-value="dialogVisible"
      :title="dialogTitle"
      style="padding: 40px"
      width="500px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        label-width="100px"
    >
      <el-text>告警分组：</el-text>
      <el-select
          v-model="GroupList"
          multiple
          placeholder="请选择告警分组"
          style="max-width: 80%"
      >
        <el-option
            v-for="item in alertGroupData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>